using System;
using SharpMud;
using SharpMud.MudLib.SAMPLE.Entities;

namespace SharpMud.MudLib.SAMPLE.Commands
{
    public class CommandManager : Server.Systems.StandardServerSystemBase
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodInfo.GetCurrentMethod().DeclaringType);

        private CommandManagerConfiguration _Config;
        private CommandMetadatum[] _CommandMetadatums;

        #region Constructors
        private CommandManager()
        {
        }

        public CommandManager(CommandManagerConfiguration config)
        {
            if (config == null)
                throw new ArgumentNullException("config");

            _Config = config;
        }
        #endregion

        protected override void _Dispose()
        {
            base._Dispose();
        }

        #region StandardServerSystemBase Tie-Ins
        protected override void _Initialize()
        {
            log.Info("Initializing...");
            base._Initialize();

            this.Reset();

            log.Info("INITIALIZED");
        }
        #endregion

        #region Private Methods
        private System.Reflection.Assembly CompileCommandsOfType(CommandTypeDefinition ctd)
        {
            log.Info("Compiling commands of type '" + ctd.FileExtension + "'...");

            System.CodeDom.Compiler.CodeDomProvider provider = (System.CodeDom.Compiler.CodeDomProvider)ctd.CodeDomProvider.AcquireTypeInstance();
            System.CodeDom.Compiler.ICodeCompiler compiler = provider.CreateCompiler();
            System.CodeDom.Compiler.CompilerResults compiler_results;
            System.CodeDom.Compiler.CompilerParameters compiler_params = new System.CodeDom.Compiler.CompilerParameters();
            string[] original_files = GetCommandFilesOfType(ctd);

            if (original_files.Length == 0)
            {
                log.Warn("No command files found!");
                return null;
            }

            compiler_params.GenerateExecutable = false;
            compiler_params.GenerateInMemory = true;
            compiler_params.IncludeDebugInformation = this._Config.IncludeDebugInformation;
            compiler_params.ReferencedAssemblies.AddRange(ActualizeAssemblyReferences(ctd.AssemblyReferences));

            log.Info("Compiling (" + original_files.Length + ") command files...");
            compiler_results = compiler.CompileAssemblyFromFileBatch(compiler_params, original_files);

            int errorcount = 0;
            int warningcount = 0;
            System.Collections.Specialized.StringCollection rslt_cmd_files = new System.Collections.Specialized.StringCollection();
            rslt_cmd_files.AddRange(original_files);
            foreach (System.CodeDom.Compiler.CompilerError ce in compiler_results.Errors)
            {
                if (ce.IsWarning)
                {
                    warningcount++;
                    log.Warn("[compiler] (" + ce.ErrorNumber + ") "
                            + "[" + ce.Line.ToString() + "," + ce.Column.ToString() + "]" + System.Environment.NewLine
                        + "{\"" + ce.FileName + "\"}" + System.Environment.NewLine
                        + "\"" + ce.ErrorText + "\"");
                }
                else
                {
                    errorcount++;
                    log.Error("[compiler] (" + ce.ErrorNumber + ") "
                        + "[" + ce.Line.ToString() + "," + ce.Column.ToString() + "]" + System.Environment.NewLine
                        + "{\"" + ce.FileName + "\"}" + System.Environment.NewLine
                        + "\"" + ce.ErrorText + "\"");
                    if (rslt_cmd_files.Contains(ce.FileName))
                        rslt_cmd_files.Remove(ce.FileName);
                }
            }
            if (errorcount == 0)
            {
                if (warningcount > 0)
                {
                    log.Warn("Command compilation COMPLETED, with 0 errors and " + warningcount.ToString() + " warnings.");
                } else {
                    log.Info("Command compilation COMPLETED, with 0 errors and " + warningcount.ToString() + " warnings.");
                }
                log.Info("Resulting Assembly = {\"" + compiler_results.CompiledAssembly.GetName().Name + "\"}");
                return compiler_results.CompiledAssembly;
            }
            else
            {
                log.Error("Command compilation FAILED, with " + errorcount.ToString() + " errors and " + warningcount.ToString() + " warnings!");
                return null;
            }
        }

        /// <summary>
        /// Takes a list of assembly references (used in the compile process) and makes
        /// sure they are in a good form for the compiler
        /// </summary>
        private string[] ActualizeAssemblyReferences(string[] assemblyReferences)
        {
            string RBF = this.RootBinaryFolder;
            System.Collections.ArrayList al = new System.Collections.ArrayList();
            foreach (string s in assemblyReferences)
            {
                al.Add(ActualizeAssemblyReference(s));
            }
            return (string[])al.ToArray(typeof(string));
        }
        /// <summary>
        /// Takes an assembly reference (used in the compile process) and makes sure it
        /// is usable. Unrecognized DLL references are deferred to the RootBinFolder, and
        /// .NET ones are made relative file names, so that the compiler can find them.
        /// </summary>
        private string ActualizeAssemblyReference(string assemblyReference)
        {
            string fn = System.IO.Path.GetFileName(assemblyReference).Trim();
            if (fn.ToLower() == "system.dll")
                return fn;
            if (fn.ToLower() == "mscorlib.dll")
                return fn;
            if (fn.ToLower() == "system.xml.dll")
                return fn;
            if (fn.ToLower() == "system.data.dll")
                return fn;
            if (fn.ToLower() == "microsoft.visualbasic.dll")
                return fn;

            return MudLibRoot.GetSubfileIntelligently(this.RootBinaryFolder, fn);
        }
        private CommandMetadatum[] ScanAssemblyForCommands(System.Reflection.Assembly assembly)
        {
            log.Info("Scanning Assembly {\"" + assembly.GetName().Name + "\"} for commands...");
            System.Collections.ArrayList al = new System.Collections.ArrayList();
            foreach (System.Type t in assembly.GetTypes())
            {
                CommandMetadatum cm = CommandMetadatum.FromLoadedType(t);
                if (cm != null)
                {
                    log.Info("Command Found: {" + cm.CommandTypeName + "}");
                    al.Add(cm);
                }
            }
            log.Info("Done scanning Assembly {\"" + assembly.GetName().Name + "\"} for commands.");
            return (CommandMetadatum[])al.ToArray(typeof(CommandMetadatum));
        }
        private string[] GetCommandFilesOfType(CommandTypeDefinition ctd)
        {
            string fe = ctd.FileExtension.Trim();
            if (!fe.StartsWith("."))
            { fe = "." + fe; }

            string[] files;

            try
            {
                files = System.IO.Directory.GetFiles(this.RootCommandsFolder, "*" + fe);
            }
            catch (System.IO.DirectoryNotFoundException e)
            {
                log.Error("DirectoryNotFoundException thrown while looking for command files",e);
                return new string[] { };
            }

            return files;
        }
        #endregion

        #region Public Methods
        public void Reset()
        {
            if (_CommandMetadatums != null)
            {
                lock (_CommandMetadatums)
                {
                    log.Warn("Restarting CommandManager...");
                    CompileAllCommands();
                    log.Info("CommandManager restarted.");
                }
            }
            else
            {
                CompileAllCommands();
            }
        }

        private void CompileAllCommands()
        {
            System.Collections.ArrayList al1 = new System.Collections.ArrayList();
            foreach (CommandTypeDefinition ctd in this._Config.CommandTypes)
            {
                System.Reflection.Assembly ass = CompileCommandsOfType(ctd);
                if (ass != null)
                    al1.Add(ass);
            }
            System.Collections.ArrayList al2 = new System.Collections.ArrayList();
            foreach (System.Reflection.Assembly ass in al1)
            {
                al2.AddRange(ScanAssemblyForCommands(ass));
            }
            _CommandMetadatums = (CommandMetadatum[])al2.ToArray(typeof(CommandMetadatum));
            log.Info("Total Commands Available: " + _CommandMetadatums.Length.ToString());
        }

        public void ExecuteCommand(Entities.ICharacter actor, string input)
        {
            ExecuteCommand(actor, actor, input);
        }
        public void ExecuteCommand(Entities.ICharacter actor, Entities.ICharacter authority, string input)
        {
            ExecuteCommand(new CommandExecutionContext(this, actor, authority, input));
        }
        private void ExecuteCommand(CommandExecutionContext context)
        {
            foreach (CommandMetadatum cm in this._CommandMetadatums)
            {
                if (cm.IsVisibleTo(context.Actor))
                {
                    foreach (SharpMud.Text.Matching.StringMatcher alias in cm.CommandAliases)
                    {
                        if (alias.IsMatch(context.CommandLineHead))
                        {
                            try
                            {
                                cm.CompiledScriptHandle.Execute(context);
                            }
                            catch (System.Exception e)
                            {
                                string logEntry
                                    = "Exception occured during command execution: " + System.Environment.NewLine
                                    + "Authority/Actor: " + context.Authority.Name + "/" + context.Actor.Name + System.Environment.NewLine
                                    + "        Command: " + context.FullCommandLine;
                                string FlogEntry
                                    = "^![yellow]Exception occured during command execution[white]: " + "^!"
                                   + "[green]Authority/Actor: [white]" + context.Authority.Name + "/" + context.Actor.Name + "^!"
                                    + "[blue]        Command: [white]" + context.FullCommandLine + "^!"
                                  + "[yellow]      Exception: [white]" + "^!" + e.ToString() + "^!";
                                log.Error(logEntry,e);
                                if (context.Actor is PlayerCharacter)
                                    (context.Actor as PlayerCharacter).Session.WriteLine(FlogEntry);
                                if ((context.Authority is PlayerCharacter) && context.Actor != context.Authority)
                                    (context.Authority as PlayerCharacter).Session.WriteLine(FlogEntry);
                            }
                            return;
                        }
                    }
                }
            }
            throw new CommandNotFoundException();
        }
        #endregion

        #region Public Properties
        public MudLib.SAMPLE.MudLibRoot HostMud
        {
            get
            {
                return (MudLib.SAMPLE.MudLibRoot)base.Host;
            }
        }
        public CommandMetadatum[] Commands
        {
            get
            {
                return this._CommandMetadatums;
            }
        }
        public string RootScriptsFolder
        {
            get
            {
                return this.HostMud.RootScriptsFolder;
            }
        }
        public string RootCommandsFolder
        {
            get
            {
                return MudLibRoot.GetSubfolderIntelligently(this.RootScriptsFolder, "commands");
            }
        }
        public string RootBinaryFolder
        {
            get
            {
                return HostMud.RootBinaryFolder;
            }
        }
        #endregion

        #region Old Code
        //		#region Private Variables
        //		private Commands.CommandsManifest		_CommandsManifest;
        //		private MudLib.SAMPLE.MudLibRoot			_Host;
        //		private System.Reflection.Assembly		_CompiledCommandAssembly;
        //		#endregion
        //		
        //		#region File System Tie-Ins
        //		public string RootScriptsFolder
        //		{
        //			get
        //			{
        //				return _Host.RootScriptsFolder;
        //			}
        //		}
        //		public string RootConfigurationFolder
        //		{
        //			get
        //			{
        //				return _Host.RootConfigurationFolder;
        //			}
        //		}
        //		public string RootBinaryFolder
        //		{
        //			get
        //			{
        //				return _Host.RootBinaryFolder;
        //			}
        //		}
        //		#endregion
        //		
        //		#region Constructors
        //		private CommandManager()
        //		{
        //		}
        //
        //		public CommandManager(MudLib.SAMPLE.MudLibRoot host)
        //		{
        //			_Host = host;
        //		}
        //
        //		#endregion
        //		
        //		#region Public Properties
        //		public Commands.CommandsManifest CommandsManifest
        //		{
        //			get
        //			{
        //				return _CommandsManifest;
        //			}
        //		}
        //
        //		public void Log(string logEntryText)
        //		{
        //			this.Host.LogManager.Write("CommandManager> " + logEntryText);
        //		}
        //
        //		public MudLib.SAMPLE.MudLibRoot Host
        //		{
        //			get
        //			{
        //				return _Host;
        //			}
        //		}
        //		/// <summary>
        //		/// The default references that are automatically included when the Commands Manifest
        //		/// is compiled into an assembly. Includes currently running/calling/entry assemblies,
        //		/// and there respective references.
        //		/// </summary>
        //		/// 
        //		public string[] DefaultAssemblyReferences
        //		{
        //			get
        //			{
        //				System.Collections.ArrayList al = new System.Collections.ArrayList();
        //				
        //				al.Add("mscorlib.dll");
        //				al.Add("System.dll");
        //				al.Add("System.Xml.dll");
        //				
        //				System.Reflection.Assembly ass;
        //
        //				//This attempts to add in every reasobable assembly that a command should
        //				//need to use.
        //				//It may prove to be excessive, or, it may prove that a more recursive search
        //				//should be done.
        //
        //				ass = System.Reflection.Assembly.GetExecutingAssembly();
        //				al.Add(ass.GetName().CodeBase);
        //
        //				ass = System.Reflection.Assembly.GetEntryAssembly();
        //				al.Add(ass.GetName().CodeBase);
        //
        //				ass = System.Reflection.Assembly.GetCallingAssembly();
        //				al.Add(ass.GetName().CodeBase);
        //
        //				for(int i=0;i<al.Count;i++)
        //				{
        //					if(((string)al[i]).ToLower().StartsWith("file:///"))
        //					{
        //						al[i] = (((string)al[i]).Substring(8,((string)al[i]).Length-8)).Replace("/",@"\");
        //					} 
        //					else if(((string)al[i]).ToLower().StartsWith("file://"))
        //					{
        //						al[i] = (((string)al[i]).Substring(7,((string)al[i]).Length-7)).Replace("/",@"\");
        //					}
        //				}
        //
        //				//Return a string array of the references to be used
        //				return (string[])al.ToArray(typeof(string));
        //			}
        //		}
        //		#endregion
        //
        //		#region Manifest Loading/Saving
        //		//public const string DefaultManifestFile = "CommandsManifest.xml";
        //		public void LoadManifest()
        //		{
        //			Log("Loading Commands Manifest...");
        //
        //			string mfd = System.IO.Path.Combine(this.RootScriptsFolder,@".\Commands");
        //
        //			
        //			if(!System.IO.Directory.Exists(mfd))
        //			{
        //				Log("Commands diretory NOT FOUND!");
        //				Log("Using blank Commands Manifest.");
        //				this._CommandsManifest = new CommandsManifest(null);
        //				return;
        //			}
        //			else
        //			{
        //				System.IO.FileStream fs;
        //				try
        //				{
        //					this._CommandsManifest = new CommandsManifest(new System.IO.DirectoryInfo(mfd));
        //				}
        //				catch(System.Exception e)
        //				{
        //					Log("Error creating Commands Manifest : " + System.Environment.NewLine + "\t" + e.Message);
        //					Log("Using blank Commands Manifest.");
        //					this._CommandsManifest = new CommandsManifest(null);
        //					return;
        //				}
        //				Log("Commands Manifest created.");
        //			}
        //		}
        //		public void SaveManifest()
        //		{
        ////			Log("[" + DateTime.Now.TimeOfDay.ToString()+  "] Saving Commands Manifest...");
        ////			string mffn = System.IO.Path.Combine(RootConfigurationFolder,DefaultManifestFile);
        ////
        ////			System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(
        ////				typeof(CommandsManifest)
        ////				//					,
        ////				//					new System.Type[] 
        ////				//				{
        ////				//					typeof(DynamicTyping.TypeLocation),	typeof(DynamicTyping.AssembliedTypeLocation),
        ////				//					typeof(DynamicTyping.ScriptedType),	typeof(DynamicTyping.FileScriptedType),
        ////				//					typeof(CommandMetadata), typeof(SharpMud.Text.Matching.StringMatcher)
        ////				//				}
        ////				);
        ////
        ////			System.IO.FileStream fs = new System.IO.FileStream(mffn,System.IO.FileMode.Create);
        ////			xs.Serialize(fs,this._CommandsManifest);
        ////			fs.Close();
        ////			Log("[" + DateTime.Now.TimeOfDay.ToString()+  "] Commands Manifest Saved.");
        //		}
        //		#endregion
        //
        //		#region Public Methods
        //		public void ExecuteCommand(object sender, string commandLine)
        //		{
        //			CommandExecutionContext cec = new CommandExecutionContext(sender,commandLine);
        //			foreach(CommandMetadata cm in this.CommandsManifest.Commands)
        //			{
        //				if(cm.CommandMatching.IsMatch(cec.CommandLineHead))
        //				{
        //					cm.CommandInstance.Execute(cec);
        //					return;
        //				}
        //			}
        //			throw new CommandNotFoundException("The command manager could not find the specified command.",cec.CommandLineHead);			
        //		}
        //		public void ExecuteCommand(Entities.ICharacter sender, string commandLine)
        //		{
        //			CharacterCommandExecutionContext cec = new CharacterCommandExecutionContext(sender,commandLine);
        //			foreach(CommandMetadata cm in this.CommandsManifest.Commands)
        //			{
        //				if(cm.CommandMatching.IsMatch(cec.CommandLineHead))
        //				{
        //					((ICharacterCommand)cm.CommandInstance).Execute(cec);
        //					return;
        //				}
        //			}
        //			throw new CommandNotFoundException("The command manager could not find the specified command.",cec.CommandLineHead);			
        //		}
        //		public void Start()
        //		{
        //			Log("CommandManager Starting....");
        //			this.LoadManifest();
        //
        //			if(this.CommandsManifest.CommandsCollection.Count == 0)
        //			{
        //				Log("No commands to compile.");
        //			}
        //			else
        //			{
        //
        //				System.CodeDom.Compiler.CompilerResults cResults = AttemptManifestCompile(true,false);
        //			
        //				if(cResults.Errors.HasErrors==false)
        //				{
        //					Log("Manifest compiling SUCCESSFUL." );
        //					this._CompiledCommandAssembly = cResults.CompiledAssembly;				
        //				}
        //				else
        //				{
        //					Log("Manifest compiling RESULTS:" );
        //					int wc=0; int ec=0;
        //					foreach(System.CodeDom.Compiler.CompilerError ce in cResults.Errors)
        //					{
        //						if(ce.IsWarning)
        //							wc++;
        //						else
        //							ec++;
        //						Host.LogManager.Write(String.Format(
        //							"***]  [{0},{1}] \"{2}\"\n" +
        //							"****] {3} - {4}"
        //							,ce.Line,ce.Column,ce.FileName,ce.ErrorNumber,ce.ErrorText
        //							));
        //					}
        //					Host.LogManager.Write(String.Format("*] {0} Warnings and {1} Errors",wc,ec));
        //					Log("Manifest compiling FAILED." );
        //					throw new CommandManifestCompileException("The Command Manager failed to compile the Commands Manifest.");
        //				}
        //				this.RegisterCompiledCommands();
        //				this.InitializeCompiledCommands();
        //			}
        //			
        //			Log("CommandManager Started.");
        //		}
        //
        //		public void Stop()
        //		{
        //			Log("CommandManager Stopping...");
        //			DisposeDisposableCompiledCommands();
        //			DeregisterCompiledCommands();
        //			Log("CommandManager Stopped.");
        //		}
        //		public void InitializeCompiledCommands()
        //		{
        //			foreach(CommandMetadata cm in this.CommandsManifest.Commands)
        //			{
        //				if(cm.CommandInstance!=null)
        //				{
        //					cm.CommandInstance.Initialize(this);
        //				}
        //			}
        //		}
        //		public void DisposeDisposableCompiledCommands()
        //		{
        //			foreach(CommandMetadata cm in this.CommandsManifest.Commands)
        //			{
        //				if(cm.CommandInstance!=null)
        //				{
        //					foreach(System.Type it in cm.CommandInstance.GetType().GetInterfaces())
        //					{
        //						if(it==typeof(System.IDisposable))
        //						{
        //							((IDisposable)cm.CommandInstance).Dispose();
        //						}
        //					}
        //				}
        //			}	
        //		}
        //		public void RegisterCompiledCommands()
        //		{
        //			Log("Registering Compiled Commands...");
        //			bool logEachCmdRegistration = true;
        //			foreach(CommandMetadata cm in CommandsManifest.Commands)
        //			{
        //				if(logEachCmdRegistration)
        //				{
        //					Host.LogManager.Write("*] Registering Command: [" + cm.Name + "]");
        //				}
        //				try
        //				{
        //					cm.RegisterCompiledCommand(this._CompiledCommandAssembly);
        //				}
        //				catch
        //				{
        //					Host.LogManager.Write("**] Failure while Registering Command [" + cm.Name + "]");
        //				}
        //			}
        //			Log("Compiled Commands Registered.");
        //		}
        //		public void DeregisterCompiledCommands()
        //		{
        //			Log("Deregistering Compiled Commands...");
        //			bool logEachCmdDeregistration = false;
        //			foreach(CommandMetadata cm in CommandsManifest.Commands)
        //			{
        //				if(logEachCmdDeregistration)
        //				{
        //					Host.LogManager.Write("*] Deregistering Command: [" + cm.Name + "]");
        //				}
        //				cm.DeregisterCompiledCommand();
        //			}
        //			Log("Compiled Commands Deregistered.");
        //		}
        //		/// <summary>
        //		/// Takes all the commands from the CommandManifest and compiles them.
        //		/// </summary>
        //		/// <param name="filterErroneousCommands">When set to True, the CompileManifest() method will
        //		/// attempt to exclude scripts in the manifest that contain errors in the compile in order to
        //		/// generate a successful compile.</param>
        //		public System.CodeDom.Compiler.CompilerResults AttemptManifestCompile(bool allowWarnings, bool filterErroneousCommands)
        //		{
        //			//Get all the different little script files
        //			System.Collections.ArrayList cmdScriptFiles = new System.Collections.ArrayList();
        //			foreach(string s in this._CommandsManifest.SourceFiles)
        //			{
        //				cmdScriptFiles.Add(s);
        //			}
        //
        //			//Build the list of referenced assemblies from the manifest
        //			System.Collections.ArrayList cmdAssemblyReferences = new System.Collections.ArrayList();
        //			foreach(AssemblyReference ar in CommandsManifest.AssemblyReferencesCollection)
        //			{
        //				string s = ar.AssemblyLocation;
        //				if(System.IO.File.Exists(System.IO.Path.Combine(RootBinaryFolder,s)))
        //				{
        //					s = System.IO.Path.Combine(RootBinaryFolder,s);
        //				}
        //				cmdAssemblyReferences.Add(s);
        //			}
        //
        //			//Get the provider (CSharp, of course)
        //			System.CodeDom.Compiler.CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
        //			System.CodeDom.Compiler.ICodeCompiler compiler = provider.CreateCompiler();
        //
        //			//Start making some compiler paramaters
        //			System.CodeDom.Compiler.CompilerParameters compileParams = new System.CodeDom.Compiler.CompilerParameters();
        //			compileParams.IncludeDebugInformation = true;
        //			compileParams.GenerateExecutable = false;
        //			compileParams.GenerateInMemory = true;
        //			compileParams.ReferencedAssemblies.AddRange((string[])cmdAssemblyReferences.ToArray(typeof(string)));
        //			//Assume every command will at least use these...
        //			compileParams.ReferencedAssemblies.AddRange(DefaultAssemblyReferences);
        //			
        //			//Declare a variable to hold the compiler results
        //			System.CodeDom.Compiler.CompilerResults results;
        //			//Attempt a compile
        //			results = compiler.CompileAssemblyFromFileBatch(compileParams,(string[])cmdScriptFiles.ToArray(typeof(string)));
        //			
        //			//Figure out what to do...
        //			if((results.Errors.HasErrors || (results.Errors.HasWarnings && allowWarnings==false))
        //				&& filterErroneousCommands==false)
        //			{
        //				//There were problems, but we aren't supposed to try and work around them,
        //				//so return the compiler results
        //				return results;
        //			}
        //			else
        //			if((results.Errors.HasErrors || (results.Errors.HasWarnings && allowWarnings==false))
        //				&& filterErroneousCommands==true)
        //			{
        //				//There were problems with the first compile.
        //				//Now we are going to try to filter out the commands that caused any errors
        //				//and then recompile.
        //				
        //				//First come up with a list of problematic files
        //				System.Collections.ArrayList excludeFiles = new System.Collections.ArrayList();
        //				foreach(System.CodeDom.Compiler.CompilerError ce in results.Errors)
        //				{
        //					if(ce.IsWarning==false || allowWarnings==false)
        //					{
        //						if(!excludeFiles.Contains(ce.FileName))
        //							excludeFiles.Add(ce.FileName);
        //					}
        //				}
        //
        //				//Now compare the files that were originally used, take out the ones that
        //				//are problematic
        //				System.Collections.ArrayList resultIncludeFiles = new System.Collections.ArrayList();
        //				foreach(string piF in cmdScriptFiles)
        //				{
        //					string pif = System.IO.Path.Combine(this.RootScriptsFolder,piF);
        //					bool fMatch = false;
        //					foreach(string eF in excludeFiles)
        //					{
        //						string ef = System.IO.Path.Combine(this.RootScriptsFolder,eF);
        //						if(System.IO.Path.GetFullPath(pif).Trim().ToLower()
        //							==
        //							System.IO.Path.GetFullPath(ef).Trim().ToLower()
        //							)
        //						{
        //							fMatch = true;
        //							break;
        //						}
        //					}
        //					if(fMatch==false)
        //						resultIncludeFiles.Add(pif);
        //					else
        //					{
        //						System.Diagnostics.Debugger.Break();
        //						return;
        //					}			
        //				}
        //				//Try compiling again
        //				results = compiler.CompileAssemblyFromFileBatch(compileParams,(string[])resultIncludeFiles.ToArray(typeof(string)));
        //			}
        //			
        //			//At this point, either the original compiled succeeded, or the corrective compile
        //			//has completed (failed or successful doesn't matter)
        //			//Return the final results.
        //			return results;
        //		}
        //
        //		public void LogErroneousCommand(CommandMetadatum cm)
        //		{
        //			Host.LogManager.Write(
        //			"CommandManager> Error Compiling Command:\n"
        //		+	"*] Command Name: " + cm.Name + "\n"
        //		+	"*] Command GUID: " + cm.Guid.ToString() + "\n"
        //		+	"*] Script File:  " + cm.ScriptFile + "\n"
        //		+	"*] An external IDE will be needed for more information."
        //				);
        //		}
        //		#endregion
        #endregion
    }
}
